package com.group11.portal.controller;


import com.group11.common.pojo.ResponseResult;

import com.group11.portal.controller.config.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    @PostMapping("upload")
    public ResponseResult<String> upload(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replace("-", "");
        //file.transferTo(new File("D://qlmimages//" + newFileName + suffix));
        //获取文件的后缀，产生以为不重复的名称
        //调用阿里云的SDK上传至OSS
        try {
            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(minioConfig.getBucketName()).object(newFileName+suffix)
                    .stream(file.getInputStream(), file.getSize(), -1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String path = minioConfig.getEndpoint() + "/" + minioConfig.getBucketName() + "/" + newFileName+suffix;
        return new ResponseResult<>(path);
    }

}
